package leetcode;

import java.util.Stack;

public class IsValid {

    public boolean isValid(String s){
        int len = s.length();
        int i = 0;
        Stack<Character> stack = new Stack<>();
        while (i < len){
            char curr = s.charAt(i++);
            char c;
            switch (curr){
                case '(':
                case '[':
                case '{':
                    stack.push(curr);
                    break;
                case ')':
                    if(stack.isEmpty()){
                        return false;
                    }
                    c = stack.pop();
                    if(c != '('){
                        return false;
                    }
                    break;
                case ']':
                    if(stack.isEmpty()){
                        return false;
                    }
                    c = stack.pop();
                    if(c != '['){
                        return false;
                    }
                    break;
                case '}':
                    if(stack.isEmpty()){
                        return false;
                    }
                    c = stack.pop();
                    if(c != '{'){
                        return false;
                    }
                    break;
            }
        }
        return stack.isEmpty();
    }

}
